package com.dzy.chiyan.activity

import android.app.DatePickerDialog
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
import com.dzy.chiyan.R
import com.dzy.chiyan.data.*
import java.util.*

// 注册
class RegisterActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)
        // 默认选中是性别男
        findViewById<RadioButton>(R.id.radiobutton_male).isChecked = true
    }
    // 点击注册
    fun onRegisterButtonClick(view: View) {
        // 获取用户输入的数据
        val inputUsername = findViewById<EditText>(R.id.edit_username).text.toString()
        val inputPassword = findViewById<EditText>(R.id.edit_password).text.toString()
        val inputConfirmPassword = findViewById<EditText>(R.id.edit_confirm_password).text.toString()
        val inputNickname = findViewById<EditText>(R.id.edit_nickname).text.toString()
        val selectedGender = getSelectedGender()
        val selectedBirthday = findViewById<Button>(R.id.button_DateSelect).text.toString()
        Log.d(
            "RegisterActivity", 
            "username: $inputUsername, password: $inputPassword, " +
            "confirmPassword: $inputConfirmPassword, nickname: $inputNickname, " +
            "gender: $selectedGender, birthday: $selectedBirthday"
        )
        // 验证输入是否合法
        if (validateInput(inputUsername, inputPassword, inputConfirmPassword, inputNickname)) {
            handleUserRegistration(inputUsername, inputPassword, inputNickname, selectedGender, selectedBirthday)
        } else {
            // 输入不合法
            Toast.makeText(this, "注册失败，请检查注册信息是否符合要求", Toast.LENGTH_SHORT).show()
        }
    }
    private fun getSelectedGender(): String {
        val genderGroup = findViewById<RadioGroup>(R.id.radioGroup_gender)
        return genderGroup.findViewById<RadioButton>(genderGroup.checkedRadioButtonId).text.toString()
    }
    private fun validateInput(username: String, password: String, confirmPassword: String, nickname: String): Boolean {
        val isUsernameValid = username.length == 11 && username.matches("\\d+".toRegex()) // 用户名为11位数字
        val isPasswordValid = password.length in 8..12 // 密码为8-12位
        val isConfirmPasswordValid = password == confirmPassword // 确认密码与密码一致
        val isNicknameValid = nickname.length in 1..20 // 昵称为1-20字符
        return isUsernameValid && isPasswordValid && isConfirmPasswordValid && isNicknameValid
    }
    // 处理注册
    private fun handleUserRegistration(
        username: String,
        password: String,
        nickname: String,
        gender: String,
        birthday: String
    ) {
        val dbHelper = DBHelper(this)
        val userDao = UserDaoImpl(dbHelper)
        // 创建用户数据对象并插入数据库
        val user = User(null, username, password)
        var registrationSuccessful = userDao.addUser(user)
        if (registrationSuccessful) {
            // 如果用户注册成功，继续添加用户详细信息
            val userId = userDao.getIdByUsername(username)
            val userInfo = UserInfo(userId, gender, birthday, nickname)
            val userInfoDao = UserInfoDaoImpl(dbHelper)
            registrationSuccessful = registrationSuccessful && userInfoDao.addUserInfo(userInfo)
        }
        dbHelper.close()
        // 根据注册结果显示提示框
        showRegistrationResultDialog(registrationSuccessful, username)
    }
    // 显示注册结果
    private fun showRegistrationResultDialog(success: Boolean, username: String) {
        val dialogBuilder = AlertDialog.Builder(this)
        if (success) {
            dialogBuilder.setTitle("注册成功")
            dialogBuilder.setMessage("账号：$username 注册成功!")
            dialogBuilder.setPositiveButton("确认") { _, _ ->
                finish()
            }
        } else {
            dialogBuilder.setTitle("注册失败")
            dialogBuilder.setMessage("账号已被注册")
        }
        dialogBuilder.create().show()
    }
    fun onCancelButtonClick(view: View) {
        finish() // 关闭当前页面
    }
    // 日期选择
    fun onDateSelectButtonClick(view: View) {
        view as Button
        val calendar = Calendar.getInstance()
        DatePickerDialog(
            this,
            { _, year, month, dayOfMonth ->
                val selectedDate = "$year-${month + 1}-$dayOfMonth"
                view.text = selectedDate // 设置按钮显示选中的日期
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        ).show()
    }
}
